package com.rla.common.utils;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.google.common.base.CaseFormat;
import com.rla.common.utils.spring.SpringUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * JSON 工具类
 *
 * @author 芋道源码
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JsonUtils {

    private static final ObjectMapper OBJECT_MAPPER = SpringUtils.getBean(ObjectMapper.class);

    public static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    public static String toJsonString(Object object) {
        if (ObjectUtil.isNull(object)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, Class<T> clazz) {
        if (StringUtils.isEmpty(text)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(text, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
        if (ArrayUtil.isEmpty(bytes)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(bytes, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, TypeReference<T> typeReference) {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(text, typeReference);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Dict parseMap(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructType(Dict.class));
        } catch (MismatchedInputException e) {
            // 类型不匹配说明不是json
            return null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<Dict> parseArrayMap(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, Dict.class));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> parseArray(String text, Class<T> clazz) {
        if (StringUtils.isEmpty(text)) {
            return new ArrayList<>();
        }
        try {
            return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public final static void underlineToHump(Object data) {
        if (data instanceof JSONArray) {
            JSONArray arr = (JSONArray) data;
            for (Object obj : arr) {
                underlineToHump(obj);
            }
        } else if (data instanceof JSONObject) {
            JSONObject json = (JSONObject) data;
            Set<String> keys = json.keySet();
            String[] arr = keys.toArray(new String[keys.size()]);
            for (String key : arr) {
                Object value = json.get(key);
                String[] key_arr = key.split("_");
                if (key_arr.length > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < key_arr.length; i++) {
                        String str = key_arr[i];
                        if (!"".equals(str)) {
                            if (i == 0) {
                                sb.append(str);
                            } else {
                                int c = str.charAt(0);
                                if (c >= 97 && c <= 122) {
                                    int v = c - 32;
                                    sb.append((char) v);
                                    if (str.length() > 1) {
                                        sb.append(str.substring(1));
                                    }
                                } else {
                                    sb.append(str);
                                }
                            }
                        }
                    }
                    json.remove(key);
                    json.put(sb.toString(), value);
                }
                underlineToHump(value);
            }
        }
    }

    public static <T extends JSON> void lowerCaseToUnderline(T json) {
        jsonKeyConverter(json, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_UNDERSCORE);
    }

    public static <T extends JSON> void underlineToLowerCase(T json) {
        jsonKeyConverter(json, CaseFormat.LOWER_UNDERSCORE, CaseFormat.LOWER_CAMEL);
    }

    public static <T extends JSON> void jsonKeyConverter(T json, CaseFormat from, CaseFormat to) {
        if (Objects.isNull(json)) {
            return;
        }
        if (json instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject)json;
            Set<String> keySet = jsonObject.keySet();
            String[] keyArray = keySet.toArray(new String[keySet.size()]);
            for (String key : keyArray) {
                Object o = jsonObject.get(key);
                if (o instanceof JSONObject) {
                    JSONObject json1 = (JSONObject)o;
                    jsonKeyConverter(json1, from, to);
                }
                Object value = jsonObject.remove(key);
                String newKey = from.to(to, key);
                jsonObject.put(newKey, value);
            }
        }

        if (json instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray)json;
            for (Object o : jsonArray) {
                if (o instanceof JSONObject) {
                    JSONObject json1 = (JSONObject)o;
                    jsonKeyConverter(json1, from, to);
                }
            }
        }
    }




}
